<template>
    <div style="padding: 10px 15px;">
        <el-card>
            <el-row type="flex" justify="space-between">
                <!-- <el-input v-model="searchValue" class="search-input" placeholder="请输入你需要搜索的内容" clearable>
            </el-input> -->
                <el-button type="primary" @click="handleAddUser">新增</el-button>
            </el-row>

            <div class="table-container">
                <el-table :data="data">
                    <el-table-column prop="userId" label="ID" align="center"></el-table-column>
                    <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
                    <el-table-column prop="auth" label="权限" align="center"></el-table-column>
                    <el-table-column label="店铺" align="center">
                        <template slot-scope="scope">
                            <span v-for="item in scope.row.userStoreDTOList" :key="item.storeId">{{ item.storeName + " "
                                }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button size="mini" @click="handleClickChange(scope.row)">修改密码</el-button>
                            <el-button size="mini" type="danger" @click="handleClickDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>

        <!-- Dialog -->
        <el-dialog title="新增用户" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
                class="demo-ruleForm cus-login-container">
                <el-form-item prop="userName" label="用户名">
                    <el-input ref="userName" type="text" v-model="ruleForm.userName" name="userName"
                        placeholder="请输入用户名" autocomplete="on" clearable></el-input>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input key="password" ref="password" type="password" v-model="ruleForm.password" name="password"
                        autocomplete="on" placeholder="请输入密码" clearable show-password></el-input>
                </el-form-item>
                <el-form-item prop="auth" label="用户等级">
                    <el-select style="width: 100%;" v-model="ruleForm.auth" placeholder="请选择权限" clearable>
                        <el-option v-for="item in authList" :label="item.label" :value="item.value"
                            :key="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="storeIds" label="店铺" v-if="ruleForm.auth == '1'">
                    <el-select style="width: 100%;" v-model="ruleForm.storeIds" multiple placeholder="请选择店铺" clearable>
                        <el-option v-for="item in storeList" :key="item.storeId" :label="item.storeName"
                            :value="item.storeId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="width: 100%;text-align: center;">
                    <el-button type="primary" class="cus-submit-btn" native-type="submit"
                        @click.native.prevent="handleSubmit">确认</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 修改密码 -->
        <el-dialog title="修改密码" :visible.sync="dialogVisiblePWD" width="40%" :close-on-click-modal="false">
            <el-form :model="pwdForm" :rules="rules_pwd" ref="pwdForm" class="demo-ruleForm cus-login-container"
                label-width="100px">
                <el-form-item prop="userName" label="用户名">
                    <el-input type="text" v-model="pwdForm.userName" disabled autocomplete="on"></el-input>
                </el-form-item>
                <el-form-item prop="oldPassword" label="原密码">
                    <el-input v-model="pwdForm.oldPassword" type="password" auto-complete="off" placeholder="请输入原密码"
                        show-password />
                </el-form-item>
                <el-form-item prop="newPassword" label="新密码">
                    <el-input v-model="pwdForm.newPassword" type="password" auto-complete="off" placeholder="请输入新密码"
                        show-password />
                </el-form-item>
                <el-form-item prop="newPassword1" label="确认密码">
                    <el-input v-model="pwdForm.newPassword1" type="password" auto-complete="off" placeholder="请输入新密码"
                        show-password />
                </el-form-item>
            </el-form>
            <div style="text-align: center;">
                <el-button type="primary" class="cus-submit-btn" native-type="submit"
                    @click.native.prevent="handleChangePwd">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import API from "../../api";
import md5 from 'js-md5';
export default {
    name: 'UserManagementInfo',
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.pwdForm.newPassword) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            currentPage1: 1,
            total: 0,
            dataLoading: false,
            data: [],
            ruleForm: {
                auth: "",
                userName: "",
                password: "",
                storeIds: []

            },
            pwdForm: {
                userName: "",
                oldPassword: "",
                newPassword: "",
                newPassword1: ""
            },
            rules: {
                userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
                password: [{ required: true, message: "请输入密码", trigger: "blur" }],
                auth: [{ required: true, message: "请选择权限", trigger: "change" }]
            },
            rules_pwd: {
                oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
                newPassword: [{ required: true, message: "请输入新密码", trigger: "blur" }],
                newPassword1: [
                    { required: true, message: "请确认密码", trigger: "blur" },
                    { validator: validatePass, trigger: "blur" }
                ]
            },
            // 与pagination对齐
            pagination: {
                defaultPageSize: 20,
                total: 0,
                defaultCurrent: 1,
            },
            searchValue: '',
            dialogVisible: false,
            dialogVisiblePWD: false,
            storeList: [],
            authList: [
                {
                    label: "工厂人员",
                    value: "3"
                },
                {
                    label: "设计人员",
                    value: "2"
                },
                {
                    label: "店铺运营人员",
                    value: "1"
                },
                {
                    label: "管理员",
                    value: "0"
                },
                {
                    label: "超级管理员",
                    value: "9"
                },
            ]
        };
    },
    computed: {
    },
    mounted() {
        this.searchData();
    },

    methods: {
        searchStoreData() {
            API.send("queryStore").then(async (res) => {
                if (res.code !== 200) {
                    this.$message.error(res.msg);
                    return;
                }
                this.storeList = res.data;
            })
        },
        searchData() {
            const loading = this.$loading({
                lock: true,
                text: this.$t('loading.login'),
                spinner: 'el-icon-loading',
            });
            API.send("getAllUser").then(async (res) => {
                if (res.code !== 200) {
                    this.$message.error(res.msg);
                    loading.close();
                    return;
                }
                res.data.forEach(a => {
                    this.authList.forEach(b => {
                        if (a.auth == b.value) {
                            a.auth = b.label;
                        }
                    })
                });
                this.data = res.data;
                loading.close();
            })
        },
        handleAddUser() {
            this.dialogVisible = true;
            this.searchStoreData();
            this.$nextTick(() => {
                this.$refs.ruleForm.resetFields();
                this.$refs.ruleForm.clearValidate();
            })
        },
        handleSubmit() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.$confirm('确认新增该用户?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const loading = this.$loading({
                            lock: true,
                            text: this.$t('loading.login'),
                            spinner: 'el-icon-loading',
                        });
                        API.send("register", {
                            data: {
                                auth: this.ruleForm.auth,
                                userName: this.ruleForm.userName,
                                storeIds: this.ruleForm.storeIds,
                                password: md5(this.ruleForm.password)
                            }
                        }).then(async (res) => {
                            if (res.code !== 200) {
                                this.$message({
                                    type: 'error',
                                    message: '新增失败!'
                                });
                                loading.close();
                                return;
                            }
                            loading.close();
                            this.$message({
                                type: 'success',
                                message: '新增成功!'
                            });
                            this.searchData();
                            this.dialogVisible = false;
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消'
                        });
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        handleChangePwd() {
            this.$refs.pwdForm.validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交修改密码申请?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const loading = this.$loading({
                            lock: true,
                            text: this.$t('loading.login'),
                            spinner: 'el-icon-loading',
                        });
                        API.send("updatePwd", {
                            data: {
                                userName: this.pwdForm.userName,
                                oldPassword: md5(this.pwdForm.oldPassword),
                                newPassword: md5(this.pwdForm.newPassword),
                                newPassword1: md5(this.pwdForm.newPassword1)
                            }
                        }).then(async (res) => {
                            if (res.code !== 200) {
                                this.$message({
                                    type: 'error',
                                    message: '修改失败!'
                                });
                                loading.close();
                                return;
                            }
                            this.dialogVisiblePWD = false;
                            loading.close();
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消'
                        });
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        handleClickChange(row) {
            this.dialogVisiblePWD = true;
            this.$nextTick(() => {
                this.$refs.pwdForm.resetFields();
                this.$refs.pwdForm.clearValidate();
                this.pwdForm.userName = row.userName;
            })
        },
        handleClickDelete(row) {
            this.$confirm('确认删除该用户?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: this.$t('loading.login'),
                    spinner: 'el-icon-loading',
                });
                API.send("deleteUser", {
                    data: {
                        userId: row.userId
                    }
                }).then(async (res) => {
                    if (res.code !== 200) {
                        this.$message({
                            type: 'error',
                            message: '删除失败!'
                        });
                        loading.close();
                        return;
                    }
                    loading.close();
                    this.searchData();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.payment-col {
    display: flex;

    .trend-container {
        display: flex;
        align-items: center;
        margin-left: 8px;
    }
}

.left-operation-container {
    padding: 0 0 6px 0;
    margin-bottom: 16px;

    .selected-count {
        display: inline-block;
        margin-left: 10px;
    }
}

.search-input {
    width: 360px;
    margin-top: 16px;
}

::v-deep .el-pagination {
    .el-pagination__total {
        float: left;
    }

    .btn-prev,
    .el-pager,
    .btn-next {
        float: right;
    }
}
</style>
